//
//  BK_SP_Fail_VC.m
//  bestkeep
//
//  Created by TOPTEAM on 2017/3/31.
//  Copyright © 2017年 utouu. All rights reserved.
//

#import "BK_SP_Fail_VC.h"
#import "BK_SPF_Status_Cell.h"
#import "BK_SPF_Action_Cell.h"
#import <Masonry.h>
#import "BKODAliManager.h"
#import "BK_SP_Success_VC.h"


#import "UIViewController+BackButtonHandler.h"


@interface BK_SP_Fail_VC ()
<
UITableViewDelegate,
UITableViewDataSource,
BK_SPF_Action_Delegate,
WXApiManagerDelegate,
BKODAliManagerDelegate
>
@property(nonatomic, strong)UITableView *tableView;
@property(nonatomic, strong)ExceptionView *exceptionView;
@property(nonatomic, strong)NSMutableArray*marr_Section;
@end

@implementation BK_SP_Fail_VC

#pragma mark-微信支付
- (void)transPayInfoToWeiXin {

    if (![WXApi isWXAppInstalled]) {
        [HUD showMessage:@"您还没有安装微信客户端"];
    }
    NSDictionary *payInfoDic = [NSJSONSerialization JSONObjectWithData:[NSData dataWithBytes:[_model.pay_info UTF8String] length:_model.pay_info.length] options:NSJSONReadingMutableLeaves error:nil];
    PayReq *req = [[PayReq alloc] init];
    req.nonceStr = payInfoDic[@"noncestr"];
    req.package = payInfoDic[@"package"];
    req.partnerId = payInfoDic[@"partnerid"];
    req.prepayId = payInfoDic[@"prepayid"];
    req.sign = payInfoDic[@"sign"];
    req.timeStamp = (UInt32)[payInfoDic[@"timestamp"] intValue];
    
    [WXApi registerApp:@"wx2c7367321c4ecab5"];
    //调微信支付
    [WXApiManager sharedManager].delegate = self;
    [WXApi sendReq:req];
}
#pragma mark-微信支付 回调
- (void)managerDidRecvPayResponse:(PayResp *)response {
    
    if (response.errCode == 0) {//支付成功
        /*
         * 支付成功---》跳转成功页面
         */
        BK_SP_Success_VC *vc=[[BK_SP_Success_VC alloc]init];
        vc.model=_model;
        [self.navigationController pushViewController:vc animated:YES];
        
    } else {
        
        /*
         * 支付失败---》跳转失败页面
         */
        //本身就在失败页面    不跳转
//        BK_SP_Fail_VC  *vc =[[BK_SP_Fail_VC alloc]init];
//        vc.pay_type=_pay_type;
//        vc.pay_info=_pay_info;
//        [self.navigationController pushViewController:vc animated:YES];
        
    }
}


#pragma mark-支付宝支付；
- (void)transPayOrder_no {
    
    [BKODAliManager manager].delegate = self;
    [[BKODAliManager manager] payRequestOrderString:_model.pay_info];
}

#pragma mark-支付宝支付回调
- (void)ODWAliManagerDidRecvPayResult:(NSDictionary *)resultDic {
    
    if ([resultDic[@"resultStatus"] isEqualToString:@"9000"]) {//支付成功
        /*
         * 支付成功---》跳转成功页面
         */

        BK_SP_Success_VC *vc=[[BK_SP_Success_VC alloc]init];
        vc.model=_model;
        [self.navigationController pushViewController:vc animated:YES];
        
    }else{
    
        
        /*
         * 支付失败---》跳转失败页面
         */
        //本身就在失败页面    不跳转
//        BK_SP_Fail_VC  *vc =[[BK_SP_Fail_VC alloc]init];
//        vc.pay_type=_pay_type;
//        vc.pay_info=_pay_info;
//        [self.navigationController pushViewController:vc animated:YES];
        
    }
}



#pragma ======= BK_SPF_Action_Delegate
- (void)BK_SPF_Action_Cancle{
    /*
     * 放弃支付
     */
    [self.navigationController popToRootViewControllerAnimated:YES];

}
- (void)BK_SPF_Action_Again{

    /*
     * 再试一次
     */
    if (_model.pay_type==10) {
        [self.navigationController popViewControllerAnimated:YES];
    }else if(_model.pay_type==20){
  
        /*
         * 支付宝支付
         */
//        [self transPayOrder_no];
        
        [self.navigationController popViewControllerAnimated:YES];
        
        
    }else if(_model.pay_type==30){
        
        /*
         * 微信支付
         */
//        [self transPayInfoToWeiXin];
        
        
        [self.navigationController popViewControllerAnimated:YES];
    }
    
}
- (void)viewDidLoad {
    [super viewDidLoad];
    [self  setProperty];
    [self  createUI];
    [self  check_NetWork];
    
}

#pragma mark==================setProperty======================
-(void)setProperty{
    
   
    
    
    self.view .backgroundColor = RGBACOLOR(242, 242, 242, 1);
    self.edgesForExtendedLayout = UIRectEdgeNone;
    self.title = @"支付结果";
    if( ([[[UIDevice currentDevice] systemVersion] doubleValue]>=7.0)) {
        self.edgesForExtendedLayout = UIRectEdgeNone;
        self.extendedLayoutIncludesOpaqueBars = NO;
        self.automaticallyAdjustsScrollViewInsets = NO;
        self.modalPresentationCapturesStatusBarAppearance = NO;
        self.navigationController.navigationBar.clipsToBounds = NO;
    }
    _marr_Section=[[NSMutableArray alloc]init];
    
}

#pragma mark==================createUI======================
-(void)createUI{
    _tableView = [[UITableView alloc] initWithFrame:CGRectZero style:UITableViewStyleGrouped];
    _tableView.backgroundColor = [UIColor clearColor];
    _tableView.showsVerticalScrollIndicator = NO;
    _tableView.separatorStyle = UITableViewCellSeparatorStyleSingleLineEtched;
    _tableView.delegate = self;
    _tableView.dataSource = self;
    
    [self.view addSubview:_tableView];
    [_tableView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.mas_equalTo(self.view);
        make.top.mas_equalTo(self.view).offset(0);
        make.bottom.mas_equalTo(self.view.mas_bottom).offset(0);
    }];
    
}
#pragma mark==================checkNet======================
-(void)check_NetWork{
    RequestReachabilityStatus status = [RequestManager reachabilityStatus];
    switch (status) {
        case RequestReachabilityStatusReachableViaWiFi:
        case RequestReachabilityStatusReachableViaWWAN: {
            /*
             *  获取小店订单详情数据
             */
            [self get_BK_StoreOrderDetail_Data];
        }
            break;
        default: {
            [HUD dismiss];
            
            self.exceptionView = [ExceptionView exceptionViewWithType:ExceptionCodeTypeNoNetwork];
            ExceptionViewAction *action = [ExceptionViewAction actionWithType:ExceptionCodeTypeNoNetwork handler:^(ExceptionViewAction *action) {
                [self.exceptionView dismiss];
                self.exceptionView = nil;
                [self check_NetWork];
            }];
            [self.exceptionView addAction:action];
            [self.exceptionView showInView:self.view];
        }
            break;
    }
}
/*
 * 获取小店订单详情数据
 */
-(void)get_BK_StoreOrderDetail_Data{
    
    NSMutableArray * marr_Cells=[[NSMutableArray alloc]init];
    
    
    CellModel* model0 =[[CellModel alloc]init];
    model0.reuseIdentifier = NSStringFromClass([BK_SPF_Status_Cell class]);
    model0.className=NSStringFromClass([BK_SPF_Status_Cell class]);
    model0.height = [BK_SPF_Status_Cell computeHeight:nil];
    model0.selectionStyle=UITableViewCellSelectionStyleNone;
    model0.accessoryType=UITableViewCellAccessoryNone;
//    [marr_Cells addObject:model0];
    
    CellModel* model1 =[[CellModel alloc]init];
    model1.reuseIdentifier = NSStringFromClass([BK_SPF_Action_Cell class]);
    model1.className=NSStringFromClass([BK_SPF_Action_Cell class]);
    model1.height = [BK_SPF_Action_Cell computeHeight:nil];
    model1.selectionStyle=UITableViewCellSelectionStyleNone;
    model1.accessoryType=UITableViewCellAccessoryNone;
    [marr_Cells addObject:model1];
  
    
    
    /*
     * 状态段
     */
    SectionModel *model_Section0=[SectionModel sectionModelWithTitle:@"" cells:@[model0]];
    model_Section0.headerhHeight=10;
    model_Section0.footerHeight=10;
    [_marr_Section addObject:model_Section0];
    

    /*
     * 按钮事件段
     */
    SectionModel *model_Section=[SectionModel sectionModelWithTitle:@"" cells:marr_Cells];
    model_Section.headerhHeight=0.0001;
    model_Section.footerHeight=0.0001;
    [_marr_Section addObject:model_Section];
    
    
    [_tableView reloadData];
}

#pragma mark tableView 代理相关
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return _marr_Section.count;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    SectionModel *sm = _marr_Section[section];
    return sm.cells.count;
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    SectionModel *sm = _marr_Section[section];
    return sm.headerhHeight;
}

- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section{
    SectionModel *sm = _marr_Section[section];
    return sm.footerHeight;
}

-(UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
    return nil;
}
-(UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section{
    return nil;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    SectionModel *sm = _marr_Section[indexPath.section];
    CellModel *cm = sm.cells[indexPath.row];
    
    return cm.height;
}


- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    SectionModel *sm = _marr_Section[indexPath.section];
    CellModel *cm = sm.cells[indexPath.row];
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cm.reuseIdentifier];
    if (!cell) {
        cell = [[NSClassFromString(cm.className) alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cm.reuseIdentifier];
    }
    cell.selectionStyle = cm.selectionStyle;
    
    
    if ([cm.className isEqualToString:NSStringFromClass([BK_SPF_Action_Cell class])]) {
        BK_SPF_Action_Cell *ex_cell=(BK_SPF_Action_Cell *)cell;
        ex_cell.delegate=self;
        
    }
    
    
    
    return cell;
}


- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    
    
    
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}



-(BOOL) navigationShouldPopOnBackButton ///在这个方法里写返回按钮的事件处理
{
    [self.navigationController popToRootViewControllerAnimated:YES];
    return YES;
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
